package com.cookie.meetproject.ui;

import android.os.Bundle;
import android.view.View;

import com.cookie.framework.adapter.CommonAdapter;
import com.cookie.framework.adapter.CommonViewHolder;
import com.cookie.framework.base.BaseBackActivity;
import com.cookie.framework.bmob.BmobManger;
import com.cookie.framework.bmob.IMUser;
import com.cookie.framework.cloud.CloudManager;
import com.cookie.framework.db.LitePalHelper;
import com.cookie.framework.db.NewFriend;
import com.cookie.framework.event.EventManager;
import com.cookie.framework.utils.CommonUtils;
import com.cookie.meetproject.R;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class NewFriendActivity extends BaseBackActivity {

    /**
     * 1.查询好友的申请
     * 2.通过适配器显示出来
     * 3.如果同意则添加对方为自己的好友
     * 4.并且发送给对方自定义消息
     * 5.对方将我添加到好友列表
     */

    private RecyclerView newFriendView;
    private View itemEmptyView;
    private Disposable disposable;
    private CommonAdapter<NewFriend> newFriendCommonAdapter;
    private List<NewFriend> list = new ArrayList<>();
    private List<IMUser> mUserList = new ArrayList<>();
    //对方用户
    private IMUser imUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_friend);
        initView();
    }

    private void initView() {
        newFriendView = (RecyclerView) findViewById(R.id.newFriendView);
        itemEmptyView = (View) findViewById(R.id.item_empty_view);
        newFriendView.setLayoutManager(new LinearLayoutManager(this));
        newFriendView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        newFriendCommonAdapter = new CommonAdapter<>(list, new CommonAdapter.OnBindDataListener<NewFriend>() {
            @Override
            public void onBindViewHolder(final NewFriend model, final CommonViewHolder viewHolder, int type, final int position) {
                //根据userID查询用户信息
                BmobManger.getInstance().queryObjectIdUser(model.getUserId(), new FindListener<IMUser>() {
                    @Override
                    public void done(List<IMUser> list, BmobException e) {
                        if (e == null) {
                            //填充具体属性
                            imUser = list.get(0);
                            mUserList.add(imUser);
                            viewHolder.setImageUrl(NewFriendActivity.this, R.id.iv_photo
                                    , imUser.getPhoto());
                            viewHolder.setImageResource(R.id.iv_sex, imUser.isSex() ?
                                    R.drawable.img_boy_icon : R.drawable.img_girl_icon);
                            viewHolder.setText(R.id.tv_nickname, imUser.getNickName());
                            viewHolder.setText(R.id.tv_age, imUser.getAge()
                                    + getString(R.string.text_search_age));
                            viewHolder.setText(R.id.tv_desc, imUser.getDesc());
                            viewHolder.setText(R.id.tv_msg, model.getMsg());

                            if (model.getIsAgree() == 0) {
                                viewHolder.getView(R.id.ll_agree).setVisibility(View.GONE);
                                viewHolder.getView(R.id.tv_result).setVisibility(View.VISIBLE);
                                viewHolder.setText(R.id.tv_result, "已同意");
                            } else if (model.getIsAgree() == 1) {
                                viewHolder.getView(R.id.ll_agree).setVisibility(View.GONE);
                                viewHolder.getView(R.id.tv_result).setVisibility(View.VISIBLE);
                                viewHolder.setText(R.id.tv_result, "已拒绝");
                            }
                        }
                    }
                });

                //同意
                viewHolder.getView(R.id.ll_yes).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        /**
                         * 1.同意则刷新当前的Item
                         * 2.将好友添加到自己的好友列表
                         * 3.通知对方我已经同意了
                         * 4.对方将我添加到好友列表
                         * 5.刷新好友列表
                         */
                        updateItem(position, 0);
                        BmobManger.getInstance().addFriend(mUserList.get(position), new SaveListener<String>() {
                            @Override
                            public void done(String s, BmobException e) {
                                if (e == null) {
                                    //保存成功之后
                                    //通知对方我已经同意了
                                    CloudManager.getInstance().sendTextMessage("", CloudManager.TYPE_AGREE_FRIEND
                                            , imUser.getObjectId());
                                    //刷新好友列表
                                    EventManager.post(EventManager.FLAG_UPDATE_FRIEND_LIST);
                                }
                            }
                        });
                    }
                });

                //拒绝
                viewHolder.getView(R.id.ll_no).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        updateItem(position, 1);
                    }
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.layout_new_friend_item;
            }
        });
        newFriendView.setAdapter(newFriendCommonAdapter);
        queryNewFriend();
    }

    //更新item
    private void updateItem(int position, int i) {
        NewFriend friend = list.get(position);
        //更新数据库
        LitePalHelper.getInstance().updateNewFriend(friend.getUserId(), i);
        //更新本地的数据源
        friend.setIsAgree(i);
        list.set(position, friend);
        newFriendCommonAdapter.notifyDataSetChanged();
    }

    //查询新朋友
    private void queryNewFriend() {
        //在子线程中获取好友列表然后在主线程中更新UI rxjava的线程调度
        disposable = Observable.create(new ObservableOnSubscribe<List<NewFriend>>() {
            @Override
            public void subscribe(ObservableEmitter<List<NewFriend>> emitter) throws Exception {
                emitter.onNext(LitePalHelper.getInstance().queryNewFriend());
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<NewFriend>>() {
                    @Override
                    public void accept(List<NewFriend> newFriends) throws Exception {
                        //更新UI
                        list.clear();
                        if (CommonUtils.isEmpty(newFriends)) {
                            itemEmptyView.setVisibility(View.GONE);
                            newFriendView.setVisibility(View.VISIBLE);
                            list.addAll(newFriends);
                        } else {
                            itemEmptyView.setVisibility(View.VISIBLE);
                            newFriendView.setVisibility(View.GONE);
                        }
                        newFriendCommonAdapter.notifyDataSetChanged();
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable.isDisposed()) {
            disposable.dispose();
        }
    }
}
